#!/bin/bash

script_dir=$(dirname $(realpath $0))
# source "${script_dir}/check-toolchain"
source "${script_dir}/config"

image="${tmpdir}/u-boot.img"
echo "u-boot image: $image"

mount | grep "${tmpdir}" | awk '{print $3}' | while read dir; do
    echo -e "\e[33mumount $dir\e[0m"
    sudo umount $dir
done


loop=$(sudo losetup -a | grep $image | grep -o -E '/dev/loop[0-9]')
if [[ ! -z $loop ]]; then
    echo -e "\e[33mdelete loop device:\e[0m sudo losetup -d $loop"
    sudo losetup -d $loop
fi

if [[ $1 != "-a" ]]; then
    exit 0
fi

loop=$(sudo losetup -f)
echo "mount to loop device: $loop"
sudo losetup $loop $image

echo "read partition table: sudo partprobe $loop"
sudo partprobe $loop

sudo fdisk -l $loop | grep "${loop}p" | awk '{print $1}' | while read part; do
    dir=${part#"$loop"}
    dir="${tmpdir}/${dir}"
    echo "mount partition: sudo mount $part $dir"
    sudo mount $part $dir
done


